/*
 * Copyright (c) 2011, 2012 Alexander Kluth <alexander.kluth@outlook.com>
 * 
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package hardyhttp.filesystem;

import java.io.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;

/**
 * Simple XML parser based on SAX for parsing the config file etc.
 * 
 * @author Alexander Kluth
 */
public class XMLParser
{
    XMLInputFactory xif;
    XMLStreamReader xmlreader;
    int event;
    
    
    /**
     * 
     */
    public XMLParser()
    {
        xif = XMLInputFactory.newInstance();
    }
    
    
    /**
     * Start parsing of the file.
     * 
     * @param filename File to parse
     * @return true if parsing was successful, false otherwise
     */
    public boolean parseFile(String filename) throws XMLStreamException
    {
        xmlreader = xif.createXMLStreamReader(new StreamSource(new File(filename)));

        return false;
    }
    
    
    /**
     * Get next element of the XML document
     * 
     * @return The name of the element, false otherwise
     * @throws XMLStreamException If something failed, throw it, so it can be catched and logged
     */
    public String getNextElement() throws XMLStreamException
    {
        event = xmlreader.next();
        
        switch (event)
        {
            case XMLStreamConstants.END_DOCUMENT:
                return null;
                
            case XMLStreamConstants.START_ELEMENT:
                return xmlreader.getLocalName();
                
            case XMLStreamConstants.CHARACTERS:
                return xmlreader.getText();
                
            case XMLStreamConstants.END_ELEMENT:
                return "END";
            
            default:
                break;
        }
        
        return null;
    }
    
    
    /**
     * Get the content of an element
     * 
     * @return The content of an element, null if we reached the end of the element
     * @throws XMLStreamException 
     */
    public String getNextElementContent() throws XMLStreamException
    {
        if (xmlreader.hasText())
            return xmlreader.getText().trim();
        
        return null;
    }
}
